package com.summer.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.summer.entity.TbUserinfo;
import com.summer.mapper.TbUserinfoMapper;
import com.summer.utils.JwtToken;
import com.summer.utils.MyUtil;
import com.summer.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author summer502
 * @since 2021-03-31
 */

@RestController
@RequestMapping("/tb-userinfo")
@CrossOrigin
@Transactional
@Api(value = "TbUserinfoController", description = "用户基本信息api")

public class TbUserinfoController {
    @Autowired (required = false)//https://blog.csdn.net/qq_40147863/article/details/86103857
    private TbUserinfoMapper tbUserinfoMapper;
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    HttpServletRequest request;
    @GetMapping("/list_tb_user_info")
    @ApiOperation("用户基本信息列表")
    public ResponseEntity list_tb_user_info(){
        QueryWrapper<TbUserinfo> wrapper = new QueryWrapper<>();
        List<TbUserinfo> list = tbUserinfoMapper.selectList(wrapper);
        ResponseEntity responseEntity;
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("list_tb_user_info",list);
        responseEntity.putDataValue("msg","成功");
        return responseEntity;
    }
    /**
     * 统计用户基本信息数量
     */
    @ApiOperation("统计用户基本信息数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        int is_delete = 0;
        QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", is_delete);
        int  count =tbUserinfoMapper.selectCount(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }


    /**
     * web登录接口
     * @param student_num
     * @param user_pwd
     *
     */
    @ApiOperation("web端登录")
    @PostMapping("/web/login")
    @ResponseBody
    public ResponseEntity login(@RequestParam(required = true) String student_num, @RequestParam(required = true) String user_pwd) throws IOException {
        ResponseEntity responseEntity = ResponseEntity.ok();
        QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_num", student_num);
        TbUserinfo userFromBase = tbUserinfoMapper.selectOne(queryWrapper);
        if(userFromBase==null){
            responseEntity =  ResponseEntity.customerError();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }
        if(userFromBase.getStudentNum().equals(student_num) &&
                userFromBase.getUser_pwd().equals(user_pwd)) {
            //给用户jwt加密生成token
            String token = JwtToken.sign(userFromBase, 60L * 1000L * 30L);//sign()方法是static修饰的，所以直接用类名调用，不需要创建对象
            //封装成对象返回给客户端
            responseEntity.putDataValue("userId",userFromBase.getUserId());
            responseEntity.putDataValue("user_name", userFromBase.getStudentNum());//调用ResponseEntity类的putDataValue方法将userID和token放进map中然后返回
            responseEntity.putDataValue("token", token);
            responseEntity.putDataValue("user_headPortrait",userFromBase.getHeadPortrait());
            /* BS架构中,客户端与服务器一连接在服务端就会自动创建一来个session对象.session.setAttribute("username",username);
这句话的意思就是自说,当客户端执行了某个操作后(刚一登陆,或其他操作)服务百端就会在session对象中存储一个名称为username的参数这个相当于hashMap,
"username" 相当于key username就是key对应的值(但注意这个值度必须是一个对象知).这样以后你可以通过session.getAttribute("username")的方法获得这个对象.
比如说,当用户道已登录系统后你就在session中存储了一个用户信息对象,此后你可以随时从session中将这个对象取出来进行一些操作,比如进行身份验证等等.
             */
        }
        else{
            responseEntity =  ResponseEntity.customerError();
            responseEntity.putDataValue("msg","账号密码错误");
        }
        return responseEntity;
    }
    /**
     * 获取当前登录用户信息
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation("web端获取当前登录用户信息")
    @PostMapping("/web/getinfo")
    @ResponseBody
    public ResponseEntity preHandle(@RequestHeader String Authorization,HttpServletResponse response) throws Exception {
        String token=Authorization;
        System.out.println(token);
        ResponseEntity responseEntity;
        //token不存在
        if (token != null) {
            responseEntity = ResponseEntity.ok();
            TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
            //解密token后的userId与用户传来的userId不一致，大多是因为token过期
            if (user != null) {
                responseEntity.putDataValue("user_id",user.getUserId());
                responseEntity.putDataValue("student_num",user.getStudentNum());
                responseEntity.putDataValue("update_time",user.getUpdate_time());
                responseEntity.putDataValue("create_time",user.getCreate_time());
                responseEntity.putDataValue("roleId",user.getRoleId());
                responseEntity.putDataValue("phone",user.getPhone());
                responseEntity.putDataValue("address",user.getAddress());
                responseEntity.putDataValue("remark",user.getRemark());
                responseEntity.putDataValue("headPortrait",user.getHeadPortrait());
                responseEntity.putDataValue("college",user.getCollege());
                responseEntity.putDataValue("grade",user.getGrade());
                responseEntity.putDataValue("major",user.getMajor());
                responseEntity.putDataValue("nickname",user.getNickname());
                responseEntity.putDataValue("openid",user.getOpenid());
                responseEntity.putDataValue("state",user.getState());
                return responseEntity;
            }
        }
        responseEntity = ResponseEntity.forbidden();
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseEntity);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
        return responseEntity;
    }

    /**
     * 修改自己信息接口
     * @param name
     * @param user_pwd
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ApiOperation("修改自己信息")
    @PostMapping("/web/update_info")
    @ResponseBody
    public ResponseEntity updateUserInfoByMyself(@RequestParam(required = false) String name,
                                                 @RequestParam(required = false) String user_pwd,
                                                 @RequestParam(required = false) String user_phone,
                                                 @RequestParam(required = false) String address,
                                                 @RequestParam(required = false) String remark,
                                                 @RequestHeader String Authorization,
                                                 HttpServletResponse response) throws IOException, ParseException {

        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo tbUserinfo = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (tbUserinfo == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","没有该用户");
        }else {
            String user_name1=tbUserinfo.getName();
            QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", user_name1);
            List<TbUserinfo> list = tbUserinfoMapper.selectList(queryWrapper);
            tbUserinfo.setName(name);
            tbUserinfo.setUser_pwd(user_pwd);
            tbUserinfo.setPhone(user_phone);
            tbUserinfo.setAddress(address);
            tbUserinfo.setRemark(remark);
            //修改信息
            tbUserinfoMapper.updateById(tbUserinfo);
            responseData = ResponseEntity.ok();
//            TbUserinfo users=userDao.selectById(user.getUserId());
//            responseData.putDataValue("users",users);
            System.out.println("修改数据成功");
        }
        return responseData;
    }

    /**
     * 管理员根据user_id修改用户信息接口可以提升权限
     * @param user_id
     * @param name
     * @param phone
     * @param address
     * @param remark
     * @param user_pwd
     * @param roleId
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ApiOperation("网页管理员根据user_id修改用户信息接口可以提升权限")
    @PostMapping("/web/update_info_id")
    @ResponseBody
    public ResponseEntity updateUsersInfoById(
            @RequestParam(required = true) Integer user_id,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String address,
            @RequestParam(required = false) String remark,
            @RequestParam(required = false) String user_pwd,
            @RequestParam(required = false) Integer roleId,
            @RequestHeader String Authorization,
            HttpServletResponse response) throws IOException, ParseException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }

        //通过查询id来判断此用户是否存在
        TbUserinfo tbUserinfo = tbUserinfoMapper.selectById(user_id);
        if (tbUserinfo == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","没有该用户");
        }else {
            if(roleId==1){
                responseData = ResponseEntity.forbidden();
                responseData.putDataValue("msg","权限不足无法提升权限");
                return responseData;
            }
            String user_name=tbUserinfo.getName();
            QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", user_name);
            List<TbUserinfo> list = tbUserinfoMapper.selectList(queryWrapper);
            responseData = ResponseEntity.ok();
            tbUserinfo.setName(name);
            tbUserinfo.setPhone(phone);
            tbUserinfo.setAddress(address);
            tbUserinfo.setRemark(remark);
            tbUserinfo.setUser_pwd(user_pwd);
            tbUserinfo.setRoleId(roleId);
            //修改信息
            tbUserinfoMapper.updateById(tbUserinfo);
            responseData.putDataValue("user_id",tbUserinfo.getUserId());
            responseData.putDataValue("user_name",tbUserinfo.getName());
            responseData.putDataValue("update_time",tbUserinfo.getUpdate_time());
            responseData.putDataValue("create_time",tbUserinfo.getCreate_time());
            responseData.putDataValue("user_role",tbUserinfo.getRoleId());
            responseData.putDataValue("phone",tbUserinfo.getPhone());
            responseData.putDataValue("address",tbUserinfo.getAddress());
            responseData.putDataValue("remark",tbUserinfo.getRemark());
            System.out.println("修改数据成功");
        }
        return responseData;
    }

//    /**
//     *
//     * @param model
//     * @param code
//     * @param rawData
//     * @param signature
//     * @param encrypteData
//     * @param iv
//     * @return
//     */
//
//    @ApiOperation("小程序注册用户")
//    @ResponseBody
//    @PostMapping("/wx/register")
//    public ResponseEntity doRegister(Model model,
//                                     @RequestParam(value = "code",required = false) String code,
//                                     @RequestParam(value = "rawData",required = false) String rawData,
//                                     @RequestParam(value = "signature",required = false) String signature,
//                                     @RequestParam(value = "encrypteData",required = false) String encrypteData,
//                                     @RequestParam(value = "iv",required = false) String iv){
//
//        ResponseEntity responseData;
//        JSONObject rawDataJson = JSON.parseObject( rawData );
//        JSONObject SessionKeyOpenId = myUtil.getcode( code );
//        String appid = SessionKeyOpenId.getString("openid" );//这里的参数是openid
//        String sessionKey = SessionKeyOpenId.getString( "session_key" );
//
//        //通过openid来查询此用户是否存在
//        QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("open_id", appid);
//        TbUserinfo tbUserinfo = tbUserinfoMapper.selectOne(queryWrapper);
//        System.out.println("当前user为：" + tbUserinfo);
//        if(tbUserinfo==null){//但是你下面换了 好像你插入进去你这个user并没有用到，那我换一下试试，但我感觉不是这个问题；我想到的是要么前端返回的参数不对，所以插入的appid没有，要不就是后端代码写不对，插不进去appid；
//            responseData = ResponseEntity.ok();
//            //入库
//            String nickName = rawDataJson.getString( "nickName" );
//            String avatar = rawDataJson.getString( "avatarUrl" );
//
//            tbUserinfo = new TbUserinfo();
//            tbUserinfo.setNickname(nickName);
//            tbUserinfo.setUser_pwd("1111");
//            tbUserinfo.setHeadPortrait(avatar);
//            tbUserinfoMapper.insert(tbUserinfo);
//            responseData.putDataValue("open_id",tbUserinfo.getOpenid());
//            responseData.putDataValue("msg","注册成功");
//            responseData.putDataValue("timestamp",myUtil.getTime());
//            System.out.println("插入数据库成功");
//            return responseData;
//        }else {
//            //已存在
//            responseData = ResponseEntity.badRequest();
//            responseData.putDataValue("msg","用户已存在");
//            responseData.putDataValue("timestamp",myUtil.getTime());
//            System.out.println("用户openid已存在,不需要插入");
//        }
//        return responseData;
//    }
//
//    /**
//     * 微信小程序登陆接口
//     * @param model
//     * @param code //用户登录凭证
//     * @param rawData  //原始数据
//     * @param signature  //署名
//     * @param encrypteData  //包括敏感数据在内的完整用户信息的加密数据
//     * @param iv  //加密算法的初始向量
//     * @return
//     * @throws UnsupportedEncodingException
//     * @throws JsonProcessingException
//     */
//    @ApiOperation("微信小程序登录")
//    @ResponseBody
//    @PostMapping("/wx/login")
//    public ResponseEntity doLogin(Model model,
//                                  @RequestParam(value = "code",required = false) String code,
//                                  @RequestParam(value = "rawData",required = false) String rawData,
//                                  @RequestParam(value = "signature",required = false) String signature,
//                                  @RequestParam(value = "encrypteData",required = false) String encrypteData,
//                                  @RequestParam(value = "iv",required = false) String iv) throws UnsupportedEncodingException, JsonProcessingException {
//        ResponseEntity responseEntity;
//        JSONObject SessionKeyOpenId = myUtil.getcode( code );
//        String appid = SessionKeyOpenId.getString("openid" );
//        //JSONObject rawDataJson = JSON.parseObject( rawData );
//        String sessionKey = SessionKeyOpenId.getString( "session_key" );
//        //通过openid来查询此用户是否存在
//        QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("open_id", appid);
//        TbUserinfo tbUserinfo = tbUserinfoMapper.selectOne(queryWrapper);
//        if(tbUserinfo == null){
//            responseEntity = ResponseEntity.badRequest();
//            responseEntity.putDataValue("msg", "用户不存在请先授权登录");
//            responseEntity.putDataValue("timestamp",myUtil.getTime());
//            return responseEntity;
//        }else {
//            responseEntity = ResponseEntity.ok();
//            //封装成对象返回给客户端
//            //给用户jwt加密生成token
//            String token = JwtToken.sign(tbUserinfo, 30L * 60L * 1000L);
//            responseEntity.putDataValue("open_id", tbUserinfo.getOpenid());
//            responseEntity.putDataValue("token", token);
//            responseEntity.putDataValue("timestamp",myUtil.getTime());
//            responseEntity.putDataValue("msg","登录成功");
//        }
//        return responseEntity;
//    }
//    /**
//     * 微信获取用户信息接口
//     * @param Authorization
//     * @param //response
//     * @return responseEntity
//     * @throws IOException
//     */
//    @ApiOperation("微信小程序获取用户信息")
//    @PostMapping("/wx/getInfo")
//    @ResponseBody
//    public ResponseEntity getWxInfo(@RequestHeader String Authorization
//            ) throws IOException {
//        ResponseEntity responseEntity;
//        String token = Authorization;
//        if (token != null) {
//            responseEntity = ResponseEntity.ok();
//            TbUserinfo tbUserinfo = JwtToken.unsign(token, TbUserinfo.class);
//            //解密token后的identity_id与用户传来的identity_id不一致，大多是因为token过期
//            if (tbUserinfo != null) {
//                responseEntity.putDataValue("user_id",tbUserinfo.getUserId());
//                responseEntity.putDataValue("open_id",tbUserinfo.getOpenid());
//                responseEntity.putDataValue("phone",tbUserinfo.getPhone());
//                responseEntity.putDataValue("update_time",tbUserinfo.getUpdate_time());
//                responseEntity.putDataValue("create_time",tbUserinfo.getCreate_time());
//                responseEntity.putDataValue("role_id",tbUserinfo.getRoleId());
//                responseEntity.putDataValue("head_portrait",tbUserinfo.getHeadPortrait());
//                responseEntity.putDataValue("nickName",tbUserinfo.getNickname());
//                responseEntity.putDataValue("is_delete",tbUserinfo.getIsDelete());
//                return responseEntity;
//            }
//        }
//        //token不存在，禁止访问
//        responseEntity = ResponseEntity.forbidden();
//        return responseEntity;
//    }
//

    /**
     * 将小程序的openid存入数据库
     * @param openid 微信用户的唯一标识
     * @return
     * @throws IOException
     */

    @ApiOperation("将小程序的openid存入数据库")
    @PostMapping("/wx/insertUser")
    @ResponseBody
    public ResponseEntity getWxInfo(@RequestParam(value = "code",required = false) String openid) throws IOException {
        ResponseEntity responseEntity;
        QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        List<TbUserinfo> list = tbUserinfoMapper.selectList(queryWrapper);
        if(list.size()>0){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","数据库已经存在成功");
            return responseEntity;
        }
        responseEntity = ResponseEntity.ok();
        TbUserinfo tbUserinfo = new TbUserinfo();
        tbUserinfo.setOpenid(openid);
        tbUserinfoMapper.insert(tbUserinfo);
        responseEntity.putDataValue("msg","数据插入成功");
        return responseEntity;
    }
}
